﻿using Financial.Business;
using Financial.Entity;
using Financial.WebApi.Models;
using Financial.WebApi.ViewModels;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Financial.WebApi.Controllers
{
    public class ExpenseController : Controller
    {
        public ActionResult Index()
        {
            var expenses = ExpenseBL.GetExpenses().ToList();

            return View(expenses);
        }

        public JsonResult GetRoot()
        {
            var records = ExpenseBL.GetExpenses(null);
            var jsonData = GetTreeData(records);
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult GetChildren(int id)
        {
            var records = ExpenseBL.GetExpenses(id);
            var jsonData = GetTreeData(records);

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        private static List<TreeDataVm> GetTreeData(List<Expense> records)
        {
            var treeData = from expense in records
                           select new TreeDataVm
                           {
                               id = expense.Id,
                               text = expense.Description,
                               children = expense.HasChildren
                           };

            return treeData.ToList();
        }
    }
}